from DataAccess.DBConnFactory import DBConnFactory
from DataAccess.blp_client import query_blp_data
from Misc.Utils import *

from datetime import date
from string import Template


def query_fx_price(currency_pair, ref_date):
	blp_field = "PX_LAST"
	isoformat_date = ref_date.isoformat()

	response = query_blp_data([currency_pair], [blp_field], ref_date, ref_date)
	#print 'debug, response from query_blp_data(["currency_pair"],,,)'
	#print response
	if response[currency_pair].has_key(isoformat_date) \
		and response[currency_pair][isoformat_date].has_key(blp_field):
		price = response[currency_pair][isoformat_date][blp_field]
		return price
	else:
		raise BLPDataError, ('Data error while getting "currency_pair":"blp_field" at ' + isoformat_date)

		
def query_fx_price_m(currency_pair_list, ref_date):
	blp_field = "PX_LAST"
	isoformat_date = ref_date.isoformat()

	response = query_blp_data(currency_pair_list, [blp_field], ref_date, ref_date)
	#print 'debug, response from query_blp_data(["currency_pair"],,,)'
	#print response
	
	r = []
	for currency_pair in currency_pair_list:
		if response[currency_pair].has_key(isoformat_date) \
			and response[currency_pair][isoformat_date].has_key(blp_field):
			price = response[currency_pair][isoformat_date][blp_field]
			dom_curncy = extract_dom_cur_from_blp_ticker(currency_pair)
			for_curncy = extract_for_cur_from_blp_ticker(currency_pair)
			#r.append((currency_pair, dom_curncy, for_curncy, price))
			r.append((isoformat_date, dom_curncy, for_curncy, price))
	
	return r

	
def update_fx_daily_price(ref_date):			 
	conn = DBConnFactory().get_db_connection('PKEDB')
	cursor = conn.cursor()
	cursor.execute('''select distinct dom_curncy,for_curncy
					from comm_fx
					where dom_curncy<>for_curncy''')
	tmp = cursor.fetchall()
	
	bb_ticks = [convert_cur_pair_to_blp_ticker(entry[0],entry[1]) for entry in tmp if entry[0]!=entry[1]]
	r = query_fx_price_m(bb_ticks, ref_date)
	#print r
	
	cursor.executemany('''merge into comm_fx fx
					using (select :1 d,:2 dc,:3 fc,:4 p from dual) t
					on (fx.ref_date=TO_DATE(t.d,'yyyy-mm-dd')
						and t.dc=fx.dom_curncy 
						and t.fc=fx.for_curncy)
					when matched then update set
						fx.price=t.p
					when not matched then insert 
						values(TO_DATE(t.d,'yyyy-mm-dd'),t.dc,t.fc,t.p)''', r)
	conn.commit()
						
						
def UNIT_TEST_insert_EURUSD_Curncy_data():
	d = date(2007, 9, 11)
	oneday = timedelta(days=1)
	
	conn = DBConnFactory().get_db_connection('PKEDB')
	cursor = conn.cursor()
	bb_ticks = ['USDEUR curncy','EURUSD curncy']
	
	while d < date.today():
				
		r = query_fx_price_m(bb_ticks, d)
		cursor.executemany('''insert into comm_fx values(:1,:2,:3,:4)''', r)
		d = d + oneday
	
	conn.commit()						